﻿using System.Linq;
using Data.Entity;

namespace ECommerce
{
	public class LocalizationManager
	{
		private static Service.ILocalStringResourceService _LocalStringResourceService;
		private static Service.ILanguageService _LanguageService;

		public static void ClearLocalResourceStringFromCache()
		{
			//SiteContext.Current.SiteCache.
		}

		public static string GetLocalResourceString(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return string.Empty;
			}

			if (SiteContext.Current == null)
			{
				return string.Empty;
			}

			var language = SiteContext.Current.WorkingLanguage;

			if (language == null)
			{
				return string.Empty;
			}

			if (SiteContext.Current.SiteCache[name + language.LanguageCulture] != null)
			{
				return SiteContext.Current.SiteCache[name + language.LanguageCulture].ToString();
			}

			if (SiteContext.Current.WorkingLanguage != null)
			{
				if (_LocalStringResourceService == null)
				{
					_LocalStringResourceService = new Service.LocalStringResourceService();
				}

				var localStrings = _LocalStringResourceService.GetLocaleStringResourceByLanguage(language.LanguageId).Where(exp => exp.ResourceName.Equals(name));

				if (localStrings != null && localStrings.Count() > 0)
				{
					var theValue = localStrings.First().ResourceValue;
					SiteContext.Current.SiteCache.Add(name + language.LanguageCulture, theValue, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new System.TimeSpan(1, 0, 0), System.Web.Caching.CacheItemPriority.Normal, null);

					return theValue;
				}
			}

			return string.Empty;
		}

		public static void ChangeCurrentCulture(int languageID)
		{
			if (languageID > 0)
			{
				if (_LanguageService == null)
				{
					_LanguageService = new Service.LanguageService();
				}

				var theCurrentLanguage = (from l in _LanguageService.GetAllLanguage()
										  where l.LanguageId.Equals(languageID)
										  select l).FirstOrDefault();

				if (theCurrentLanguage != null)
				{
					var culture = new System.Globalization.CultureInfo(theCurrentLanguage.LanguageCulture);
					System.Threading.Thread.CurrentThread.CurrentCulture = culture;
					System.Threading.Thread.CurrentThread.CurrentUICulture = culture;

					SiteContext.Current.SetCookie(SiteContext.COOKIE_KEY_LANGUAGECULTURE, theCurrentLanguage.LanguageCulture);
					SiteContext.Current.WorkingLanguage = theCurrentLanguage;
				}
			}
		}
	}
}
